#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Comm.hpp"

using namespace std;

void Usage(const std::string &process)
{
    std::cout << "Usage: " << process << " server_ip server_port" << std::endl;
}

int main(int argc, char* argv[])
{   
    if(argc != 3)
    {
        Usage(argv[1]);
        return 1;
    }

    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if(sock < 0)
    {
        cerr << "Socket error~" << endl;
        return 2;
    }
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(AF_INET, serverip.c_str(), &server.sin_addr);// 1. 字符串ip->4字节IP 2. 网络序列

    int n = connect(sock, CONV(&server), sizeof(server)); // 自动进行bind哦！
    if(n < 0)
    {
        cerr << "connect error" << endl;
        return 2;
    }

    // 并没有向server一样，产生新的sockfd.未来我们就用connect成功的sockfd进行通信即可.
    while(true)
    {
        string inbuffer;
        cout << "please enter~" << endl;
        getline(cin, inbuffer);

        ssize_t n = write(sock, inbuffer.c_str(), inbuffer.size());
        if(n > 0)
        {
            char buffer[1024];
            ssize_t m = read(sock, buffer, sizeof(buffer)-1);
            if(m > 0)
            {
                buffer[m] = 0;
                cout << "get a echo messsge -> " << buffer << endl;
            }else if(m < 0||m == 0)
            {
                break;
            }
        }else{
            break;
        }
    }
    close(sock);
    return 0;
}